import { resetObject } from "@/utils/index.js";
const bodyHeight = document.querySelector("body").offsetHeight;

export const listMixin = {
  data: function () {
    return {
      list: [],
      listKey: "", // 列表中每条数据的唯一标识字段
      listRowStyle: {
        cursor: "pointer"
      },
      tableHeight: "100%",
      tableHeightFixed: "20rem",
      inputWidth: "calc(100% - 40px)",

      selected: [], // 已选数据
      total: 0, // 总数据条数
      page: 1, // 分页
      pageSize: 20, // 分页大小
      pageSizes: [20, 50, 100, 200],
      pageLayout: "sizes, prev, pager, next",
      activeRow: 0, // 当前激活的行m

      fixedBottom: false // 是否出现下方页数悬浮条
    };
  },

  mounted () {
    window.onresize = () => {
      this.fixedBottom = document.documentElement.clientHeight < window.screen.height;
    };
    const scrollElem = document.querySelector(".app-main");
    scrollElem.onscroll = () => {
      if ((scrollElem.scrollTop + document.body.clientHeight) >= scrollElem.scrollHeight) {
        this.fixedBottom = false;
      } else {
        this.fixedBottom = true;
      }
    };
  },

  watch: {
    list: {
      deep: true,
      handler () {
        if (this.page !== 1 && !this.list.length) {
          this.page--;
          this.readList();
        }
      }
    }
  },

  computed: {
    /* 已选数据的条数 */
    totalSelected () {
      return this.selected.length;
    },

    /* 根据已选条数判断按钮是否可点击 */
    listBtnDisabled () {
      return !this.totalSelected ? true : false;
    },

    // 是否显示斑马线
    isStripe() {
      return this.$store.state.settings.isStripe;
    }
  },

  filters: {
    /* 格式化货币值 */
    formatMoney ( number ) {
      const n = 2; // 保留小数
      const s = parseFloat((number + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
      const l = s.split(".")[0].split("").reverse();
      const r = s.split(".")[1];
      let t = "";
      for ( let i = 0; i < l.length; i ++ ) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
      }
      return "￥" + t.split("").reverse().join("") + "." + r;
    },

    /* 格式化日期 */
    formatDate ( date ) {
      const dealDate = date.split("、");
      let str = "";
      dealDate.forEach(i => {
        const list = i.split("-");
        const month = Number(list[1]) > 9 ? list[1] : "0" + list[1];
        const day = Number(list[2]) > 9 ? list[2] : "0" + list[2];
        str += list[0] + "年" + month + "月" + day + "日、";
      });
      return str.substring( 0, str.length - 1 );
    }
  },

  methods: {
    readList () {
      // 每个列表自己的获取数据的方法需要重写
    },

    /* 重置搜索，需要将搜索条件设置为filter字段名 */
    resetSearch () {
      resetObject(this.filter);
      this.page = 1;
      this.pageSize = 20;
      this.readList();
    },

    /* el-table-column的formatter方法，目前作用是将空数据显示为- */
    emptyFormatter (row, column) {
      if (!column.property) return "--";
      else if (!row[column.property] && row[column.property] !== 0) return "--";
      else return row[column.property];
    },

    /* 高级搜索功能, 默认调用readList()方法 */
    adSearch () {
      this.page = 1;
      this.readList();
    },

    /* 自动勾选在已选列表中的行, 一般在readList()中触发 */
    /* 需要目标列表设置ref="tableList" */
    /* 其中key为列表每行的唯一标识 */
    autoSelectList () {
      const key = this.listKey;
      const target = this.$refs.tableList;
      if ( target ) {
        this.list.forEach((row, index) => {
          const catchItem = this.selected.find(i => {
            return i[key] === row[key];
          });
          if ( catchItem ) {
            setTimeout(() => {
              target.toggleRowSelection( this.list[index], true );
            }, 50);
          }
        });
      }
    },

    tableRowClassName ({ row, rowIndex }) {
      if ( row === this.activeRow ) return "active-row";
    },

    /* 单选某一行的选项时触发 */
    handleSelect ( selection, row ) {
      const key = this.listKey;
      /* 判断操作为选中还是取消选中 */
      const isSelect = !!selection.find(i => {
        return i[key] === row[key];
      });

      /* 判断是否存在已选列表中 */
      const isInSelectedList = this.selected.findIndex(i => {
        console.log(i, row);
        return i[key] === row[key];
      });
      /* 选中则添加进已选列表中 */
      if ( isSelect && isInSelectedList === -1 ) this.selected.push( row );

      /* 取消选中则从selected列表中删除 */
      if ( !isSelect && isInSelectedList !== -1 ) {
        this.selected.splice( isInSelectedList, 1 );
      }
      // console.log(this.selected);
    },

    /* 全选时触发 */
    handleSelectAll ( selection ) {
      const key = this.listKey;
      if ( selection.length ) {
        /* 全选操作 */
        selection.forEach(row => {
          const catchRow = this.selected.find(i => {
            return i[key] === row[key];
          });
          if ( !catchRow ) this.selected.push( row );
        });
      } else {
        /* 全不选操作 */
        this.list.forEach(row => {
          const index = this.selected.findIndex(i => {
            return i[key] === row[key];
          });
          if ( index !== -1 ) this.selected.splice( index, 1 );
        });
      }

    },

    /* 选项改变时触发 */
    handleSelectedChange (selection) {
      // this.$logger.log("当前已选列表:", this.selected);
    },

    // 分页大小改变
    handleSizeChange (val) {
      this.pageSize = val;
      this.page= 1;
      this.readList();
    },

    // 分页改变
    handleCurrentChange (index) {
      this.page = index;
      this.readList();
    }
  }
};
